<template>
  <lay-dropdown
    placement="bottom-end"
    updateAtScroll
    @show="handleVisibleChange"
  >
    <template #content>
      <lay-card>
        <!-- <lay-space> -->
        <div class="flex-boxs">
          <p style="font-size: 16px; font-weight: 600">自定义列</p>
          <p style="color: #8a8a8a">勾选需要是示的列，拖动列名进行排序。</p>
        </div>
        <div class="popover-title">
          <a-button size="small" type="link" @click="reset">
            重置排序
          </a-button>
        </div>
        <!-- </lay-space> -->
        <div class="check-item">
          <div style="padding: 4px 16px 8px 0">
            <SliderIcon class="pr-6px cursor-move iconStyle" />
            <lay-checkbox
              v-model="checkIndex"
              skin="primary"
              value="index"
              @change="handleIndexCheckChange"
            >
              序号列
            </lay-checkbox>
          </div>
        </div>
        <div ref="columnListRef" class="table-setting-boxs">
          <template
            v-for="item in tableColumns"
            :key="table.getColumnKey(item)"
          >
            <div class="check-item">
              <div style="padding: 4px 16px 8px 0">
                <SliderIcon
                  class="table-column-drag-icon pr-6px cursor-move iconStyle"
                />
                <lay-checkbox
                  v-model="item.showInTable"
                  value=""
                  skin="primary"
                >
                  {{ item.title }}
                </lay-checkbox>
              </div>
            </div>
          </template>
        </div>
        <lay-space>
          <p>锁定前</p>
          <lay-input-number v-model="fixedNum"></lay-input-number>
          <p>列</p>
        </lay-space>
      </lay-card>
    </template>
    <SetIcon />
    <!-- </lay-tooltip> -->
  </lay-dropdown>
</template>

<script lang="ts" setup>
import { watch, ref } from "vue";
import { SliderIcon, PrevIcon, NextIcon, SetIcon } from "@layui/icons-vue";
import { cloneDeep } from "lodash-es";
import { useTableContext } from "../../hooks/useTableContext";
import type { TableColumn } from "../../types/column";
import { useSortable } from "../..//hooks/useSortable";
import { isNullAndUnDef } from "../../../../../utils/is";

const table = useTableContext();
const fixedNum = ref<number>(0);
let inited = false;
const tableProps = table.getProps;
let defaultColumns = cloneDeep<TableColumn[]>(tableProps.value.columns);

const defaultShowIndex = !!table.enableIndexRow;
const tableColumns = ref<TableColumn[]>([]);

const checkIndex = ref(defaultShowIndex);
const columnListRef = ref<HTMLDivElement>();

// 初始化选中状态
const initCheckStatus = () => {
  // @ts-ignore
  tableColumns.value = cloneDeep(defaultColumns);
  tableColumns.value.forEach((item) => (item.showInTable = true));
  checkIndex.value = defaultShowIndex;
  fixedNum.value = tableProps.value.lockColumnCount || 0;
};
initCheckStatus();
watch(
  tableColumns,
  (columns) => {
    table.setProps({ columns });
  },
  {
    deep: true,
  },
);
watch(
  () => tableProps.value.columns,
  (newVal, val) => {
    if (newVal?.length != val?.length) {
      console.log("我变了啊", newVal);
      defaultColumns = cloneDeep<TableColumn[]>(newVal);
      initCheckStatus();
    }
  },
  {
    deep: true,
  },
);
watch(fixedNum, (val) => {
  let newCol = tableProps.value.columns.map((_, index) => {
    let fixed = undefined;
    if (index < val - 1) {
      fixed = "left";
    }
    return {
      ..._,
      fixed,
    };
  });
  table.setProps({ columns: newCol, fixedIndex: val > 0 ? "left" : undefined });
});
// 设置序号列
const handleIndexCheckChange = (e: any) => {
  console.log(e);
  table.setProps({ enableIndexRow: e });
};
async function handleVisibleChange() {
  // if (inited) return;
  await nextTick();
  const columnListEl = unref(columnListRef);
  if (!columnListEl) return;

  // Drag and drop sort
  const { initSortable } = useSortable(columnListEl, {
    handle: ".table-column-drag-icon",
    onEnd: (evt) => {
      const { oldIndex, newIndex } = evt;
      if (
        isNullAndUnDef(oldIndex) ||
        isNullAndUnDef(newIndex) ||
        oldIndex === newIndex
      ) {
        return;
      }
      // Sort column
      const columns = tableColumns.value;
      columns.splice(newIndex, 0, columns.splice(oldIndex, 1)[0]);
    },
  });
  initSortable();
  inited = true;
}
// handleVisibleChange()
const reset = () => {
  initCheckStatus();
  table.setProps({ enableIndexRow: defaultShowIndex });
};
</script>

<style lang="less" scoped>
.check-item {
  @apply flex justify-between;
}

.column-fixed {
  .fixed-right,
  .fixed-left {
    &.active,
    &:hover {
      color: #1890ff;
    }
  }
}
.table-setting-boxs {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  .check-item {
    width: calc(50% - 4px);
  }
}
.iconStyle {
  color: #0b484259;
  margin: 0 5px;
}
.flex-boxs {
  display: inline-flex;
  > p {
    padding: 10px;
  }
}
.popover-title {
  float: right;
  padding: 10px;
  color: var(--global-primary-color) !important;
}
</style>
